package xw.qxypt.modules.baseinfo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import xw.qxypt.common.utils.MapGPSTranslateUtil;
import xw.qxypt.common.utils.WeatherTranslateUtil;
import xw.qxypt.common.utils.XinZhiUtil;
import xw.qxypt.modules.baseinfo.entity.*;
import xw.qxypt.modules.baseinfo.service.*;
import xw.qxypt.modules.sys.shiro.ShiroUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("homepageService")
public class HomepageServicempl implements HomepageService {
    @Autowired
    private LhpEquipmentService lhpEquipmentService;
    @Autowired
    private LhpAlertService lhpAlertService;
    @Autowired
    private LhpDataRoadDetectorService lhpDataRoadDetectorService;
    @Autowired
    private LhpInstallationPointService lhpInstallationPointService;
    @Autowired
    private LhpHighwaySectionService lhpHighwaySectionService;
    @Autowired
    private LhpWaysectGpsService lhpWaysectGpsService;

    @Override
    public List<LhpAlertEntity> showAlertByUserAndElement(@RequestParam Map<String, Object> params) {
        String type= (String)params.get("type");
        if("3".equals(type)){
            type= "visibility";
        }
        if("1".equals(type)){
            type= "roadSurfaceTemp";
        }
        if("2".equals(type)){
            type= "friction";
        }
        if("4".equals(type)){
            type= "waterFilmHeight";
        }
        if("5".equals(type)){
            type= "airTemp";
        }
        if("6".equals(type)){
            type= "relativeHumidity";
        }
        if("7".equals(type)){
            type= "windSpeed";
        }
        if("8".equals(type)){
            type= "precipitation";
        }
        List<LhpAlertEntity> fanhui = new ArrayList();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE, -10);
        String startTime = df.format(c.getTime());
        // 根据用户id找到不同设备类型的设备集合(气象站,路面探测器,能见度仪)
        List<LhpEquipmentEntity> equipList = lhpEquipmentService.getEquipmentByUserId(ShiroUtils.getUserId());
        List<String> equipmentIdList = new ArrayList<String>();
        // 获取不同设备类型id的集合
        for (LhpEquipmentEntity e : equipList) {
            equipmentIdList.add(e.getId());
        }

        // 根据设备id的集合找到这些设备的报警信息
        if (equipmentIdList.size() > 0) {
            // alertList4 = lhpAlertService.queryAlertByEquipmentList(equipmentIdList2, startTime);
            fanhui = lhpAlertService.list(
                    new QueryWrapper<LhpAlertEntity>()
                            .gt("alert_time",startTime)
                            .in("equipment_id",equipmentIdList)
                            .eq("alert_type",type)
            );

        }

        // 遍历路面温度list，如果温度《0且路面状态不为10才报警
        /*Iterator<LhpAlertEntity> it = fanhui.iterator();
        while (it.hasNext()) {
            LhpAlertEntity l = it.next();
            if("roadSurfaceTemp".equals(l.getAlertType())) {
                Double temp = Double.parseDouble(l.getAlertValue());
                if (temp < 0) {
                    Date time = l.getAlertTime();
                    String equipmentId = l.getEquipmentId();
                    LhpDataRoadDetectorEntity ldrd = lhpDataRoadDetectorService.getOne(
                            new QueryWrapper<LhpDataRoadDetectorEntity>()
                                    .eq("data_time", time)
                                    .eq("equipment_id", equipmentId)
                    );
                    if (ldrd != null) {
                        if ("10".equals(ldrd.getRoadCondition())) {
                            it.remove();
                        }
                    }
                }
            }
        }*/
        //用安装点名称替换安装点id
        List<LhpInstallationPointEntity> pointList=lhpInstallationPointService.list();
        for(LhpAlertEntity alertEntity:fanhui){
            for(LhpInstallationPointEntity pointEntity:pointList){
                if(alertEntity.getPointId().equals(pointEntity.getId())){
                    alertEntity.setPointName(pointEntity.getPointName());
                }
            }
        }
        return fanhui;
    }

    @Override
    public Map<String, Integer> checkEquipmengStatus() {
        List<LhpEquipmentEntity> equipList = lhpEquipmentService.getEquipmentByUserId(ShiroUtils.getUserId());
        Map<String,Integer> map = new HashMap<>();
        map.put("00",0);
        map.put("10",0);
        map.put("20",0);
        map.put("30",0);
        map.put("01",0);
        map.put("11",0);
        map.put("21",0);
        map.put("31",0);
        for(LhpEquipmentEntity lee : equipList){
            String key = lee.getEquipmentType()+""+lee.getEquipmentStatus()+"";
            int count = map.get(key);
            map.put(key,count+1);
        }
        //如果有综合设备，将每种设备+1
        if(map.get("00") != 0){
            map.put("10",map.get("10")+map.get("00"));
            map.put("20",map.get("20")+map.get("00"));
            map.put("30",map.get("30")+map.get("00"));
        }
        if(map.get("01") != 0){
            map.put("11",map.get("11")+map.get("01"));
            map.put("21",map.get("21")+map.get("01"));
            map.put("31",map.get("31")+map.get("01"));
        }
        map.put("njdOnline",map.get("10"));
        map.put("njdOffline",map.get("11"));
        map.put("qxzOnline",map.get("20"));
        map.put("qxzOffline",map.get("21"));
        map.put("dmtcqOnline",map.get("30"));
        map.put("dmtcqOffline",map.get("31"));
        return map;
    }

    @Override
    public Map showAlertByUser() {
        List<LhpAlertEntity> fanhui = new ArrayList();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE, -10);
        String startTime = df.format(c.getTime());
        // 根据用户id找到不同设备类型的设备集合(气象站,路面探测器,能见度仪)
        List<LhpEquipmentEntity> equipList = lhpEquipmentService.getEquipmentByUserId(ShiroUtils.getUserId());
        List<String> equipmentIdList = new ArrayList<String>();
        // 获取不同设备类型id的集合
        for (LhpEquipmentEntity e : equipList) {
            equipmentIdList.add(e.getId());
        }

        // 根据设备id的集合找到这些设备的报警信息
        if (equipmentIdList.size() > 0) {
           // alertList4 = lhpAlertService.queryAlertByEquipmentList(equipmentIdList2, startTime);
            fanhui = lhpAlertService.list(
                    new QueryWrapper<LhpAlertEntity>()
                            .gt("alert_time",startTime)
                            .in("equipment_id",equipmentIdList)
            );

        }

        // 遍历路面温度list，如果温度《0且路面状态不为10才报警
        /*Iterator<LhpAlertEntity> it = fanhui.iterator();
        while (it.hasNext()) {
            LhpAlertEntity l = it.next();
            if("roadSurfaceTemp".equals(l.getAlertType())) {
                Double temp = Double.parseDouble(l.getAlertValue());
                if (temp < 0) {
                    Date time = l.getAlertTime();
                    String equipmentId = l.getEquipmentId();
                    LhpDataRoadDetectorEntity ldrd = lhpDataRoadDetectorService.getOne(
                            new QueryWrapper<LhpDataRoadDetectorEntity>()
                                    .eq("data_time", time)
                                    .eq("equipment_id", equipmentId)
                    );
                    if (ldrd != null) {
                        if ("10".equals(ldrd.getRoadCondition())) {
                            it.remove();
                        }
                    }
                }
            }
        }*/
        Map<String,List<LhpAlertEntity>> infoMap = new HashMap();
        //用安装点名称替换安装点id
        List<LhpInstallationPointEntity> pointList=lhpInstallationPointService.list();
        for(LhpAlertEntity alertEntity:fanhui){
            for(LhpInstallationPointEntity pointEntity:pointList){
                if(alertEntity.getPointId().equals(pointEntity.getId())){
                    alertEntity.setPointName(pointEntity.getPointName());
                }
            }
            //将alert按类型分组
            if(infoMap.containsKey(alertEntity.getAlertType())){
                infoMap.get(alertEntity.getAlertType()).add(alertEntity);
            }else{
                List<LhpAlertEntity> a = new ArrayList<>();
                a.add(alertEntity);
                infoMap.put(alertEntity.getAlertType(),a);
            }
        }
        Map map = new HashMap();
        map.put("fanhui",fanhui);
        if(infoMap.containsKey("roadSurfaceTemp")){
            map.put("roadSurfaceTemp",infoMap.get("roadSurfaceTemp").size());
        }else{
            map.put("roadSurfaceTemp",0);
        }
        if(infoMap.containsKey("friction")){
            map.put("friction",infoMap.get("friction").size());
        }else{
            map.put("friction",0);
        }
        if(infoMap.containsKey("waterFilmHeight")){
            map.put("waterFilmHeight",infoMap.get("waterFilmHeight").size());
        }else{
            map.put("waterFilmHeight",0);
        }
        if(infoMap.containsKey("visibility")){
            map.put("visibility",infoMap.get("visibility").size());
        }else{
            map.put("visibility",0);
        }
        if(infoMap.containsKey("airTemp")){
            map.put("airTemp",infoMap.get("airTemp").size());
        }else{
            map.put("airTemp",0);
        }
        if(infoMap.containsKey("relativeHumidity")){
            map.put("relativeHumidity",infoMap.get("relativeHumidity").size());
        }else{
            map.put("relativeHumidity",0);
        }
        if(infoMap.containsKey("windSpeed")){
            map.put("windSpeed",infoMap.get("windSpeed").size());
        }else{
            map.put("windSpeed",0);
        }
        if(infoMap.containsKey("precipitation")){
            map.put("precipitation",infoMap.get("precipitation").size());
        }else{
            map.put("precipitation",0);
        }
        return  map;
    }



     @Override
   public List getMarkerWeather(HttpServletRequest request) {
         String gxgps = request.getParameter("xgps");
         String gygps = request.getParameter("ygps");
         double[] arr = MapGPSTranslateUtil.gcj02_To_Gps84(
                 Double.parseDouble(gygps), Double.parseDouble(gxgps));
         String xgps = arr[1] + "";
         String ygps = arr[0] + "";
         List<Object> list = new ArrayList<Object>();
         try {
             XinZhiUtil caiyun=new XinZhiUtil();

             String result1 =caiyun.getRealWeatherByLatitudeAndLongitude(xgps, ygps, null);
             JSONObject obj = JSONObject.fromObject(result1);

             String status = obj.get("status").toString();
             HashMap realMap = new HashMap();
             if (status.equals("ok")) {
                 JSONObject result = obj.getJSONObject("result");

                 String resultStatus = result.get("status").toString();

                 if (resultStatus.equals("ok")) {

                     String temperature = result.get("temperature").toString();

                     String skycon = result.get("skycon").toString();

                     String conArr1[] = WeatherTranslateUtil.getSkycon(skycon);
                     String skyConName = conArr1[0];
                     String cloudrate = result.get("cloudrate").toString();
                     String aqi = result.get("aqi").toString();
                     String humidity = result.get("humidity").toString();
                     String pres = result.get("pres").toString();
                     String pm25 = result.get("pm25").toString();

                     JSONObject precipitation = result
                             .getJSONObject("precipitation");

                     JSONObject nearest = precipitation.getJSONObject("nearest");

                     JSONObject local = precipitation.getJSONObject("local");
                     // 最近下雨带雨强
                     String nearestintensity="";
                     String distance="";
                     String nestRanType = "";
                     if(!nearest.isNullObject()) {
                         nearestintensity = nearest.get("intensity").toString();
                         distance = nearest.get("distance").toString();
                         double distanceNum = Double.parseDouble(distance);

                         if (distanceNum >= 10000) {
                             distance = "无降雨";
                         } else {
                             distance += "公里";
                             nestRanType = WeatherTranslateUtil
                                     .getRainTypeByIntensity(nearestintensity);
                         }
                     }


                     // 本地雨强
                     String localintensity = local.get("intensity").toString();

                     String localRanType = WeatherTranslateUtil
                             .getRainTypeByIntensity(localintensity);

                     JSONObject wind = result.getJSONObject("wind");

                     String speed = wind.get("speed").toString();
                     double fsValue = Double.parseDouble(speed);
                     String fsDj = WeatherTranslateUtil
                             .getWindDjByValue(fsValue);

                     String direction = wind.get("direction").toString();
                     String fx = WeatherTranslateUtil.getWindDirByNum(direction);
                     realMap.put("temperature", temperature);
                     realMap.put("skyCon", skycon);
                     realMap.put("skyConName", skyConName);
                     realMap.put("cloudrate", cloudrate);
                     realMap.put("aqi", aqi);
                     String humVal = "";
                     DecimalFormat df = new DecimalFormat("0.00");
                     if(!"".equals(humidity)){

                         double v=Double.parseDouble(humidity)*100;
                         humVal = df.format(v);
                     }
                     realMap.put("humidity", humVal);
                     realMap.put("pres", pres);
                     realMap.put("pm25", pm25);

                     realMap.put("distance", distance);
                     realMap.put("nestRanType", nestRanType);
                     realMap.put("localRanType", localRanType);
                     realMap.put("speed", speed);
                     realMap.put("fsDj", fsDj);
                     realMap.put("direction", direction);
                     realMap.put("fx", fx);

                 }
             }

             //call.setOperationName("getWeatherByLatitudeAndLongitude");
             // 查询天气预报
             //String result2 = (String) call.invoke(new Object[] { xgps, ygps });
             String result2 =caiyun.getWeatherByLatitudeAndLongitude(xgps, ygps, null);

             list.add(realMap);
             list.add(result2);

         } catch (Exception e) {
             e.printStackTrace();
         }
         return list;
     }

    @Override
    public  List<MapPloylineModel> getRoadLines() {

        List<MapPloylineModel> mapPolyList = new ArrayList<MapPloylineModel>();
        // 查询用户下的所有路段
        List<String> waysectIds = lhpHighwaySectionService.findWaysectIdByUser(ShiroUtils.getUserId());
        for (String sectId : waysectIds) {
            List<String> objList = new ArrayList<>();// 经纬度集合
            List<String> gpsIdList = new ArrayList<>();// gpsId 集合
            List<LhpWaysectGpsEntity> gpsList = lhpWaysectGpsService.list(
                    new QueryWrapper<LhpWaysectGpsEntity>()
                            .eq("waysect_id",sectId)
            );
            for (int i = 0; i < gpsList.size(); i++) {
                LhpWaysectGpsEntity gpsM = gpsList.get(i);
                objList.add(gpsM.getXGaode() + "," + gpsM.getYGaode());
            }
            MapPloylineModel model = new MapPloylineModel();
            model.setPolySectId(sectId);
            model.setPolyArr(objList);
            model.setPolyColor("green");
            model.setSectGpsId(gpsIdList);
            // model.setAlarmLevel(alarmLevel+"" );
            mapPolyList.add(model);
        }
        return mapPolyList;
    }

}
